import json

from exts import db
from utils import JSEncoder


class User(db.Model):
    __tablename__ = "user"
    user_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(255), nullable=False)
    password = db.Column(db.String(255), nullable=False)
    email = db.Column(db.String(255), nullable=False, unique=True)
    nickname = db.Column(db.String(255))
    avatar = db.Column(db.String(255))
    create_time = db.Column(db.DateTime, nullable=False)
    update_time = db.Column(db.DateTime, nullable=False)

    def __repr__(self):
        fields = self.__dict__
        if "_sa_instance_state" in fields:
            del fields["_sa_instance_state"]
        return json.dumps(fields,cls=JSEncoder)

    def __str__(self):
        return self.__repr__()

    def to_dict(self):
        return json.loads(self.__str__())


class Category(db.Model):
    __tablename__ = "category"
    category_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    category_name = db.Column(db.String(32), nullable=False, unique=True)
    category_alias = db.Column(db.String(32))
    create_user_id = db.Column(db.Integer, nullable=False)
    create_user_name = db.Column(db.String(255), nullable=False)
    create_time = db.Column(db.DateTime, nullable=False)
    update_time = db.Column(db.DateTime, nullable=False)

    def __repr__(self):
        fields = self.__dict__
        if "_sa_instance_state" in fields:
            del fields["_sa_instance_state"]
        return json.dumps(fields,cls=JSEncoder)

    def __str__(self):
        return self.__repr__()

    def to_dict(self):
        return json.loads(self.__str__())


class Article(db.Model):
    __tablename__ = "article"
    article_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(32), nullable=False, unique=True)
    content = db.Column(db.Text)
    category_id = db.Column(db.Integer, nullable=False)
    state = db.Column(db.String(10), nullable=False, default="0")
    cover_img = db.Column(db.String(255))
    create_user_id = db.Column(db.Integer, nullable=False)
    create_user_name = db.Column(db.String(255), nullable=False)
    create_time = db.Column(db.DateTime, nullable=False)
    update_time = db.Column(db.DateTime, nullable=False)

    def __repr__(self):
        fields = self.__dict__
        if "_sa_instance_state" in fields:
            del fields["_sa_instance_state"]
        return json.dumps(fields,cls=JSEncoder)

    def __str__(self):
        return self.__repr__()

    def to_dict(self):
        return json.loads(self.__str__())